package com.chang.soul.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.fastjson.JSONObject;
import com.chang.soul.Listen.ExcelListener;
import com.chang.soul.bean.PaperBean;
import com.chang.soul.bean.PaperQueryForm;
import com.chang.soul.conf.JwtIgnore;
import com.chang.soul.service.PaperService;
import com.chang.soul.util.Result;
import com.chang.soul.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/paper")
@Api("试题管理接口")
public class PaperController {

    @Autowired
    PaperService paperService;


    /**
     * 测试Excel导入
     */
    @ApiOperation(value = "文件导入", notes = "无需Token", httpMethod = "POST")
    @PostMapping("/importExcel")
    @JwtIgnore
    public Result importExcel(@RequestParam("file") MultipartFile file) {

        try {
            File targetFile = new File(System.getProperty("user.dir") + "/file" + "/test.xlsx");
            file.transferTo(targetFile);

            ExcelListener excelListener = new ExcelListener();

            // 工作簿，对应的是一个excel文件
            ExcelReaderBuilder readWorkBook = EasyExcel.read(System.getProperty("user.dir") + "/file" + "/test.xlsx",
                    PaperBean.class, excelListener);
            // 工作表，对应一个sheet。 一个工作簿里面可以含有多个工作表
            ExcelReaderSheetBuilder sheet = readWorkBook.sheet();
            //读
            sheet.doRead();

            //获取数据
            List<Object> list = excelListener.getDatas();
            System.out.println(list);
            PaperBean paperBean = new PaperBean();
            for (int i = 0; i < list.size(); i++) {
                paperBean = (PaperBean) list.get(i);
                if (!paperService.insertPaper(paperBean)) {
                    return ResultUtil.error("insert fail!");
                }
            }
            return ResultUtil.success("insert success!");
        } catch (Exception e) {
            System.out.println(e);
            return ResultUtil.error("导入失败");
        }
        /**
         * 参考链接
         * https://www.jianshu.com/p/78cc1729fbd1
         */
    }

    @ApiOperation(value = "分页模糊查询所有试题", notes = "无需token", httpMethod = "POST")
    @PostMapping("/getAllPaperList")
    @JwtIgnore
    public Result getAllPaperList(@Valid @RequestBody PaperQueryForm paperQueryForm) {
        Integer currentPage = paperQueryForm.getCurrentPage();
        Integer pageSize = paperQueryForm.getPageSize();
        currentPage = currentPage == null || currentPage <= 0 ? 1 : currentPage;
        pageSize = pageSize == null || pageSize <= 0 ? 1 : pageSize;
        Integer startNum = (currentPage - 1) * pageSize;
        paperQueryForm.setCurrentPage(startNum);
        paperQueryForm.setPageSize(pageSize);

        List<PaperBean> list = paperService.getAllPaperList(paperQueryForm);
        int total = paperService.getCountByPaperList(paperQueryForm);
        JSONObject res = new JSONObject();
        res.put("currentPage", currentPage);
        res.put("pageSize", pageSize);
        res.put("totalCount", total);
        res.put("list", list);
        System.out.println(res);
        return ResultUtil.success(res);
    }

    @ApiOperation(value = "删除试题接口", notes = "无需token", httpMethod = "POST")
    @PostMapping("/deletePaperById")
    @JwtIgnore
    public Result deletePaperById(@RequestParam(value = "id") Integer id) {
        boolean flag = paperService.deletePaperById(id);
        if (!flag) {
            return ResultUtil.error("delete from paper fail");
        }
        return ResultUtil.success("delete from paper sucess");
    }

    @ApiOperation(value = "更新试题接口", notes = "无需token", httpMethod = "POST")
    @PostMapping("/updatePaper")
    @JwtIgnore
    public Result updatePaper(@Valid @RequestBody PaperBean myPaperBean) {
        PaperBean paperBean = paperService.getPaperById(myPaperBean.getId());

        paperBean.setPaperBrief(myPaperBean.getPaperBrief());
        paperBean.setQuestionStem(myPaperBean.getQuestionStem());
        paperBean.setOptionA(myPaperBean.getOptionA());
        paperBean.setScoreA(myPaperBean.getScoreA());
        paperBean.setOptionB(myPaperBean.getOptionB());
        paperBean.setScoreB(myPaperBean.getScoreB());
        paperBean.setOptionC(myPaperBean.getOptionC());
        paperBean.setScoreC(myPaperBean.getScoreC());
        paperBean.setOptionD(myPaperBean.getOptionD());
        paperBean.setScoreD(myPaperBean.getScoreD());
        paperBean.setOptionE(myPaperBean.getOptionE());
        paperBean.setScoreE(myPaperBean.getScoreE());
        paperBean.setOptionF(myPaperBean.getOptionF());
        paperBean.setScoreF(myPaperBean.getScoreF());
        paperBean.setOptionG(myPaperBean.getOptionG());
        paperBean.setScoreG(myPaperBean.getScoreG());

        if (paperService.updatePaper(paperBean)) {
            return ResultUtil.success("update paper success");
        } else {
            return ResultUtil.error("update paper fail");
        }
    }

    @ApiOperation(value = "插入试题接口", notes = "无需token", httpMethod = "POST")
    @PostMapping("/insertPaper")
    @JwtIgnore
    public Result insertPaper(@Valid @RequestBody PaperBean myPaperBean) {
        System.out.println(myPaperBean);

        if (!paperService.insertPaper(myPaperBean)) {
            return ResultUtil.error("insert fail!");
        }
        return ResultUtil.success("insert success!");
    }

    @ApiOperation(value = "获取每套试卷的具体试题", notes = "无需token", httpMethod = "GET")
    @GetMapping("/getPapersByPapId")
    @JwtIgnore
    public Result getPapersByPapId(@RequestParam(value = "paperId") Integer paperId) {
        List<PaperBean> paperList = paperService.getPapersByPapId(paperId);
        if (paperList == null) {
            return ResultUtil.error("此 paperId 对应内容为空");
        } else {
            System.out.println("paperList" + paperList);
            return ResultUtil.success(paperList);
        }
    }

    // 文件上传 （可以多文件上传）
    @ApiOperation(value = "文件上传", notes = "无需token", httpMethod = "POST")
    @PostMapping("/upload")
    @JwtIgnore
    public Result fileUploads(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {

        String filePath = "G:\\textFile\\";
        // 日志打印
        Logger log = LoggerFactory.getLogger("UploadPaperController");

        // 获取上传的文件名称
        String fileName = file.getOriginalFilename();
        File file1 = new File(filePath);
        //判断上传文件的保存目录是否存在
        if (!file1.exists() && !file1.isDirectory()) {
            System.out.println(filePath + "目录不存在，需要创建");
            //创建目录
            file1.mkdir();
        }

        // 得到文件保存的位置以及新文件名
        File dest = new File(filePath + fileName);
        try {
            // 上传的文件被保存了
            file.transferTo(dest);
            // 打印日志
            log.info("上传成功，当前上传的文件保存在 {}", filePath + fileName);
            // 自定义返回的统一的 JSON 格式的数据，可以直接返回这个字符串也是可以的。
            return ResultUtil.success("文件上传成功");
        } catch (IOException e) {
            log.error(e.toString());
        }
        // 待完成 —— 文件类型校验工作
        return ResultUtil.error("上传错误");
    }

    /*可删*/
    @ApiOperation(value = "下载文件", notes = "无需token", httpMethod = "GET")
    @GetMapping("/downLoadPaper")
    @JwtIgnore
    public Result downLoadPaper(@RequestParam(value = "filename") String filename, String savePath, HttpServletResponse response) throws ServletException, IOException {
        //得到要下载的文件名
        String fileName = filename;
        System.out.println(fileName);
        //fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
        //上传的文件都是保存在G:\textFile目录下
        String fileSaveRootPath = "G:\\textFile\\";
        //通过文件名找出文件的所在目录
        //String path = findFileSavePathByFileName(fileName,fileSaveRootPath);

        //得到要下载的文件
        File file = new File(fileSaveRootPath + fileName);
        System.out.println(fileSaveRootPath + fileName);
        //如果文件不存在
        if (!file.exists()) {
            return ResultUtil.error("文件不存在，下载失败");
        }
        /*//处理文件名
        String realname = fileName.substring(fileName.indexOf("_") + 1);
        System.out.println("realname"+realname);*/
        //设置响应头，控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //读取要下载的文件，保存到文件输入流
        FileInputStream in = new FileInputStream(fileSaveRootPath + fileName);
        //创建输出流

        OutputStream out = response.getOutputStream();
        //FileOutputStream out1 = new FileOutputStream(savePath);
        //创建缓冲区
        byte buffer[] = new byte[1024];
        int len = 0;
        //循环将输入流中的内容读取到缓冲区当中
        while ((len = in.read(buffer)) > 0) {
            //输出缓冲区的内容到浏览器，实现文件下载
            out.write(buffer, 0, len);
        }
        //关闭文件输入流
        in.close();
        //关闭输出流
        out.close();
        return ResultUtil.success("下载成功");
    }


}
